package com.thinkit.bigdata.web.controller;

import com.thinkit.bigdata.core.ConfigHelper;
import com.thinkit.bigdata.core.util.DateFormatUtil;
import com.thinkit.bigdata.core.util.TaskUtil;
import com.thinkit.bigdata.core.util.es.ESUtil;
import com.thinkit.bigdata.web.coremet.SystemStatic;
import com.thinkit.bigdata.web.model.BaseEntity;
import com.thinkit.bigdata.web.model.bus.BusWorkWithBLOBs;
import com.thinkit.bigdata.web.model.result.Constants;
import com.thinkit.bigdata.web.model.result.HtmlResult;
import com.thinkit.bigdata.web.model.sec.User;
import com.thinkit.bigdata.web.service.perCenter.MyAssService;
import com.thinkit.bigdata.web.service.perCenter.PerCenterService;
import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.net.UnknownHostException;
import java.util.*;

@RestController
@RequestMapping("/home")
public class HomeController {

    private static Logger logger = Logger.getLogger(HomeController.class);

    @Resource
    private PerCenterService perCenterService;

    @Resource
    private MyAssService myAssService;

    @Resource
    private ESUtil esUtil;

    @RequestMapping(value = "/get-title", method = RequestMethod.POST)
    public HtmlResult getTitle(HttpServletRequest request) throws UnknownHostException {
        String logTxt = "【首页代办任务】";
        logger.info(logTxt);
        String seatId = request.getParameter("seatId");//坐席工号
        logger.info(logTxt + "seatId = " + seatId);
        //任务条件组装
        List<BusWorkWithBLOBs> works = perCenterService.getWorksByTime();
        if (works.isEmpty()) {
            return HtmlResult.success("没有待办任务");
        }
        List<Map<String, Object>> resultMap = new ArrayList<>();
        //查询每个任务的提示信息
        for (BusWorkWithBLOBs work : works) {
            BoolQueryBuilder boolQuery = new BoolQueryBuilder();
            Session session = SecurityUtils.getSubject().getSession();
            int userIdentity = (Integer) session.getAttribute("userIdentity");
            String account = null;
            if (BaseEntity.USERIDENTITY_ZX == userIdentity) {//质检
                User userInfo = (User) SecurityUtils.getSubject().getSession().getAttribute(Constants.SESSION_USER_INFO);
                account = userInfo.getAccount();
            }
            //数据权限
            esUtil.formatQ(boolQuery, account);
            esUtil.taskFormatQ(boolQuery, "", work.getId().toString(), "");
            //代办任务 随录信息条件
            esUtil.taskFormVoice(boolQuery, request, "【首页代办任务】");
            long sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.AUDIO_ES_INDEX, SystemStatic.AUDIO_ES_TYPE, boolQuery);
            logger.info("获取数据条数为：" + sum);
            if (sum > 0) {
                Map<String, Object> taskMap = new HashMap<>();
                taskMap.put("workId", work.getId());
                taskMap.put("workName", work.getWorkname());
                taskMap.put("workType", work.getWorktype());
                taskMap.put("workNum", sum);
                taskMap.put("daysRemaining", "-");
                if (work.getProstatus() == BaseEntity.TASK_PROSTATUS_TEST_OVER) {
                    taskMap.put("daysRemaining", esUtil.taskIs(logTxt, work));
                }
                resultMap.add(taskMap);
            }
        }
        return HtmlResult.success(resultMap);
    }


    @RequestMapping(value = "/get--my-ass-data", method = RequestMethod.POST)
    public HtmlResult getDataListByHome(HttpServletRequest request) {
        String logTxt = "【获取我的考核信息】";
        logger.info(logTxt);
        try {
            //获取当前时间的范围
            //获取当前月第一天：
            String[] first = DateFormatUtil.dateToString(new Date(), DateFormatUtil.yyyy_MM_dd).split("-");
            request.setAttribute("monthlyAssess", first[0] + first[1]);
            BoolQueryBuilder boolQuery = myAssService.getQuery(logTxt, request);
            List<String> docList = new ArrayList<>();
            //总条数
            Integer sum = SystemStatic.crud.queryQBuilderAllByMes(SystemStatic.COUNT_ES_INDEX, SystemStatic.COUNT_ES_TYPE, boolQuery);
            //单词查询条数
            int excleMax = ConfigHelper.getInt("export.data.sheet.max.number", 1000);
            List<Integer> pageTout = TaskUtil.formatSum(sum, excleMax);//todo最后一个数字需要特殊处理:6022
            for (Integer aPageTout : pageTout) {
                List<String> docs  = SystemStatic.crud.queryMapQBuilderList(
                        SystemStatic.COUNT_ES_INDEX,
                        SystemStatic.COUNT_ES_TYPE,
                        aPageTout,
                        excleMax,
                        boolQuery,
                        "",
                        ""
                );
                docList.addAll(docs);
            }
            return HtmlResult.success(docList);
        } catch (Exception e) {
            e.printStackTrace();
            return HtmlResult.failure("数据获取异常");
        }
    }
}
